package com.guigu.guilimall.auth.controller;

import com.atguigu.common.constant.AuthServiceConstant;
import com.atguigu.common.exception.CodeEnum;
import com.atguigu.common.utils.R;
import com.guigu.guilimall.auth.entity.vo.MemberRegisterVo;

import com.guigu.guilimall.auth.entity.vo.UserLoginVo;
import com.guigu.guilimall.auth.feign.MemberFeignService;
import com.guigu.guilimall.auth.feign.ThirdPartFeignService;
import lombok.extern.log4j.Log4j2;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Controller;
import org.springframework.validation.BindingResult;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import javax.servlet.http.HttpSession;
import javax.validation.Valid;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;

@Log4j2
@Controller
public class LoginController {

    @Autowired
    private ThirdPartFeignService thirdPartFeignService;

    @Autowired
    StringRedisTemplate redisTemplate;

    @Autowired
    MemberFeignService memberFeignService;

    @GetMapping("/sms/tst")
    @ResponseBody
    public void tst() {
        System.out.println("ok");


    }

    @GetMapping("/sms/sendCode")
    @ResponseBody
    public R sendCode(@RequestParam("phone") String phone) {
        log.info("发送短信 phone={}",phone);
        String redisCode = redisTemplate.opsForValue().get(AuthServiceConstant.SMS_CODE_PREFIX + phone);
        if (StringUtils.isNotEmpty(redisCode)){
            long s = Long.parseLong(redisCode.split("_")[1]);
            if (System.currentTimeMillis()-s<60000){
                return R.error(CodeEnum.SMS_CODE_EXCEPTION);
            }
        }
        String substring = UUID.randomUUID().toString().substring(0, 4)+"_"+System.currentTimeMillis();

        redisTemplate.opsForValue().set(AuthServiceConstant.SMS_CODE_PREFIX+phone,substring,10, TimeUnit.MINUTES);
  /*      SmsSendAo smsAo=new SmsSendAo();
        smsAo.setCode(substring.split("_")[0]);
        smsAo.setPhone(phone);
        R r = thirdPartFeignService.sendSms(smsAo);*/
        return R.ok();
    }

    @PostMapping("/register")
    public String regist(@Valid MemberRegisterVo userRegistVo, BindingResult result,
            /* 模拟重定向携带数据*/RedirectAttributes redirectAttributes) {

        log.info("用户注册");
        if (result.hasErrors()) {
            //效验出错
            Map<String, String> error = result.getFieldErrors().stream()
                    .collect(Collectors.toMap(FieldError::getField, FieldError::getDefaultMessage));

            redirectAttributes.addFlashAttribute("errors", error);
            return "redirect:/reg.html";
        }

        String code = redisTemplate.opsForValue().get(AuthServiceConstant.SMS_CODE_PREFIX + userRegistVo.getPhone());
        if (StringUtils.isNotEmpty(code)){
            if (userRegistVo.getCode().equals(code.split("_")[0])){
              //  redisTemplate.delete(AuthServiceConstant.SMS_CODE_PREFIX + userRegistVo.getPhone());
                //调用会员注册接口
                R r = memberFeignService.register(userRegistVo);
                if (r.getCode()==0){
                    return "redirect:/login.html";
                }else {
                    Map<String, String> map=new HashMap<>();
                    map.put("msg", "验证码错误");
                    redirectAttributes.addFlashAttribute("errors", map);
                    return "redirect:/reg.html";
                }
            }else {
                Map<String, String> map=new HashMap<>();
                map.put("msg", "验证码错误");
                redirectAttributes.addFlashAttribute("errors", map);
                return "redirect:/reg.html";

            }
        }else {
            Map<String, String> map=new HashMap<>();
            map.put("msg", "验证码错误");
            redirectAttributes.addFlashAttribute("errors", map);
            return "redirect:/reg.html";

        }
    }

    @PostMapping("/login")
    public String indexPage(UserLoginVo vo,RedirectAttributes redirectAttributes){
        R login = memberFeignService.login(vo);
        if (login.getCode()==0){
            return "redirect:http://localhost:8070/index.html";
        }else {
            Map<String, String> map=new HashMap<>();
            map.put("msg", "验证码错误");
            redirectAttributes.addFlashAttribute("errors", map);
            return "redirect:/reg.html";
        }
    }


    @GetMapping({"login.html"})
    public String indexPage(HttpSession httpSession){
        if (httpSession.getAttribute(AuthServiceConstant.LOGIN_REDIS_USER)!=null){
            return "redirect:http://localhost:8070/index.html";
        }
        return "login";
    }

    /*

    @GetMapping({"reg.html"})
    public String reg(){


        return "reg";
    }*/
}
